package com.jf.cloud.payment.allinpay.util;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.allinpay.sdk.OpenClient;
import com.allinpay.sdk.bean.BizParameter;
import com.allinpay.sdk.bean.OpenConfig;
import com.allinpay.sdk.bean.OpenResponse;
import com.jf.cloud.common.exception.LuckException;
import com.jf.cloud.common.response.ResponseEnum;
import com.jf.cloud.payment.allinpay.AbstractReq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @author LGH
 */
public class AllinpayUtil {

	private static final Logger LOG = LoggerFactory.getLogger(AllinpayUtil.class);
	public static final String METHOD_PREFIX = "allinpay.yunst.";

	protected static OpenClient client;

	public static void configClient() {
		final String url = "http://test.allinpay.com/open/gateway";
		final String appId = "661520093552836608";
		final String secretKey = "CRcZWcErbbuOwwCPwsrqOtoIDwGmTJCa";
		final String privateKeyPath = "/Users/renhd/work/cert/661520093552836608.pfx";
		final String pwd = "123456";
		final String tlPublicKey = "/Users/renhd/work/cert/TLCert-test.cer";

		final OpenConfig oc = new OpenConfig(url, appId, secretKey, privateKeyPath, pwd, tlPublicKey);
		try {
			client = new OpenClient(oc);
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}


	public static <T> T sendData(AbstractReq req, Class<T> clazz){
		String responseData = getResponseData(req);
		if (clazz == null) {
			return null;
		}
		return JSON.parseObject(responseData, clazz);
	}

	public static <T> List<T> sendDataGetArray(AbstractReq req, Class<T> clazz){
		String responseData = getResponseData(req);
		if (clazz == null) {
			return null;
		}
		return JSON.parseArray(responseData, clazz);
	}

	private static String getResponseData(AbstractReq req) {
		String method = METHOD_PREFIX + req.getService() + StrUtil.C_DOT + req.getMethod();
		// 为啥要这样，因为通联的jar比较辣鸡，不支持直接传字符串，只能传对象，而且里面的方法都还私有的
		BizParameter bizParameter = JSON.parseObject(JSON.toJSONString(req), BizParameter.class);
		final OpenResponse response = client.execute( method, bizParameter);
		LOG.info(JSON.toJSONString(response));
		if (ResponseEnum.OK.getMsg().equals(response.getSubCode())) {
			return response.getData();
		}
		throw new LuckException(response.getSubMsg());
	}
}
